Skip to main content

diff command

diff - compare files line by line

The diff command in Linux is a utility used to compare two files and display their differences. It’s very useful for spotting changes in code, configuration files, or any text data.

Usage: diff [OPTION]... [FILES]...

  • OPTION: Flags which enhances the diff abilities.
  • FILES: The file(s) to compare.

Common Options

OptionDescription
-uUnified output with context
-ySide-by-side output
-iIgnore case differences
-wIgnore all whitespace
-bIgnore changes in whitespace amount
-rRecursively compare directories
-qBrief mode (just say if files differ)

Examples

  • Basic Comparison

    Run diff with two files to see how they differ.

    $ diff file1.txt file2.txt
    • Sample files:
      • file1.txt: apple\nbanana\ncherry
      • file2.txt: apple\norange\ncherry
    • Output:
      2c2
      < banana
      ---
      > orange
    • Explanation:
      • 2c2: Line 2 in file1 changed to line 2 in file2.
      • < banana: Line from file1.
      • > orange: Line from file2.

    If the files are identical, there’s no output.

  • Unified Output Format

    Use -u for a more readable "unified" format, showing context around changes.

    $ diff -u file1.txt file2.txt
    • Output:
      --- file1.txt   2025-03-29 10:00:00
      +++ file2.txt 2025-03-29 10:01:00
      @@ -1,3 +1,3 @@
      apple
      -banana
      +orange
      cherry
    • Explanation:
      • - lines are removed from file1.
      • + lines are added in file2.
      • Context lines (unchanged) are shown for reference.
  • Side-by-Side Output

    Use -y to display differences in two columns.

    $ diff -y file1.txt file2.txt
    • Output:
      apple           apple
      banana | orange
      cherry cherry
    • Explanation:
      • | indicates a difference.
      • Identical lines align without markers.
  • Ignoring Case

    Use -i to ignore case differences.

    $ diff -i file1.txt file2.txt
    • If file1.txt has "Apple" and file2.txt has "apple", -i treats them as the same.
  • Ignoring Whitespace

    Use -w to ignore all whitespace differences or -b to ignore changes in the amount of whitespace.

    $ diff -w file1.txt file2.txt
    • Ignores spaces or tabs (e.g., "hello world" vs. "helloworld").
  • Recursive Directory Comparison

    Use -r to compare directories and their contents.

    $ diff -r dir1/ dir2/
    • Compares all files in dir1 and dir2, reporting differences.
  • Brief Output

    Use -q to only report whether files differ, not how.

    $ diff -q file1.txt file2.txt
    • Output: Files file1.txt and file2.txt differ (or nothing if identical).
$ diff --help